package com.physics.mps.module.fastcae.builder;

import com.physics.mps.common.exception.BusinessException;
import com.physics.mps.entity.enums.CodeEnum;
import com.physics.mps.module.fastcae.vo.FastcaeMeshData;
import com.physics.mps.module.util.PyUtils;
import lombok.Data;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author mcsoft
 * @since 2024/2/21
 */
@Data
public class FastcaeMeshBuilder {
    /**
     * 网格参数
     */
    private FastcaeMeshData meshData;

    public FastcaeMeshBuilder(FastcaeMeshData meshData) {
        this.meshData = meshData;
    }

    /**
     * 生成网格划分脚本
     * @return
     */
    private String meshPy() {
        StringBuilder builder = new StringBuilder();
        builder.append("MainWindow.importGeometry(\"").append(meshData.getStpPath()).append("\")").append(PyUtils.WRAP);
        builder.append("while Geometry.isEmpty(): continue").append(PyUtils.WRAP);
        builder.append("gmsher = Mesher.Gmsher()").append(PyUtils.WRAP);
        builder.append("gmsher.setDim(3)").append(PyUtils.WRAP);
        builder.append("gmsher.selectedAll()").append(PyUtils.WRAP);
        builder.append("gmsher.setElementType(\"").append(meshData.getElementType()).append("\")").append(PyUtils.WRAP);
        builder.append("gmsher.setElementOrder(").append(meshData.getElementOrder()).append(")").append(PyUtils.WRAP);
        builder.append("gmsher.setMethod(").append(meshData.getMethod()).append(")").append(PyUtils.WRAP);
        builder.append("gmsher.setSizeFactor(").append(meshData.getSizeFactor()).append(")").append(PyUtils.WRAP);
        builder.append("gmsher.setMinSize(").append(meshData.getMinSize()).append(")").append(PyUtils.WRAP);
        builder.append("gmsher.setMaxSize(").append(meshData.getMaxSize()).append(")").append(PyUtils.WRAP);
        builder.append("gmsher.cleanGeo()").append(PyUtils.WRAP);
        builder.append("gmsher.startGenerationThread()").append(PyUtils.WRAP);
        builder.append("exit(0)").append(PyUtils.WRAP);

        return builder.toString();
    }

    /**
     * 网格划分脚本写入文件
     * @param path
     * @return
     */
    public String writeToPy(String path) {
        try {
            Files.write(Paths.get(path), meshPy().getBytes());
        } catch (IOException e) {
            throw new BusinessException(CodeEnum.FILE_WRITE_FAILED);
        }
        return path;
    }
}
